﻿using System;
using System.Web;
using System.Web.Mvc;
using Lilium.Unity.Adapters;
using Lilium.Unity.ContainerConfiguration;
using Lilium.Web.Mvc.EntityFilters;
using Lilium.Web.Mvc.Metadata;
using Microsoft.Practices.Unity;
using Lilium.Unity.MvcHttpApplication;

namespace Lilium.Web.Mvc
{
    public class UnityApplication : System.Web.HttpApplication, IContainerProvider
    {
        public override void Init()
        {
            base.Init();

            var container = new UnityContainer();
            InitializeContainer(container);
            m_RootContainer = container;

            ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(this));
        }

        #region IContainerProvider Members

        public IUnityContainer GetContainer()
        {
            return RootContainer;
        }

        #endregion

        protected virtual void InitializeContainer(IUnityContainer container)
        {
            if (container == null) throw new ArgumentNullException("container");

            container.AddNewExtension<MvcHttpApplicationExtension>();
        }

        #region private IUnityContainer RootContainer

        private static IUnityContainer m_RootContainer;

        private static IUnityContainer RootContainer
        {
            get
            {
                return m_RootContainer;
            }
        }

        #endregion
    }
}